﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Fleck;
using Newtonsoft.Json;
using TiTi.tea.Comm;

namespace TiTi.tea.Api.WebSocket
{
    public class FleckServer
    {
        static Dictionary<Guid, IWebSocketConnection> managerSockets = new Dictionary<Guid, IWebSocketConnection>();
        static Dictionary<Guid, IWebSocketConnection> customerSockets = new Dictionary<Guid, IWebSocketConnection>();
        public static void CreateServer()
        {
            var server = new WebSocketServer("ws://127.0.0.1:9898");
            
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    var conInfo = socket.ConnectionInfo;
                    if (conInfo.Origin.IndexOf("http://localhost:8080")>=0) managerSockets.Add(conInfo.Id, socket); 
                    else customerSockets.Add(conInfo.Id, socket);
                    Console.WriteLine("已打开服务器");
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("已关闭服务器");
                };
                socket.OnMessage = (msg) =>
                {
                    SendMessage(msg.FormJsonTo<ClientMessage>());
                    //Console.WriteLine(msg);
                    //socket.Send("这里是服务器"+msg);
                };
            });
            //Console.ReadLine();
            //server.Dispose();
        }

        async public static void SendMessage(ClientMessage msg)
        {
            string sendMsg = null;
            switch (msg.Message)
            {
                case "addOrder":
                    sendMsg = "getOrders";
                    break;
                default:
                    return;
                    break;
            }
            
            foreach (var item in (msg.ClientType==1? customerSockets:managerSockets).Values)
            {
                item.Send(sendMsg);
            }
        }
    }
}